package cn.hpclub.server.controller.admin;

import java.sql.SQLException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.model.Permission;
import cn.hpclub.server.model.SysRolePermission;
import cn.hpclub.server.util.InterfaceUtil;

public class PermissionController extends BaseAdminController<Permission>{

    /**
     * @Title: list
     * @Description:获取列表
     */
    public void list(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();

        Permission permission = new Permission();
        findByPageForSearch(permission.getSelect(), permission.getSqlExceptSelect(searchInfo));
        setAttrs(searchInfo);

        render("/admin/permission_list.tpl");
    }

    /**
     * @Title: add
     * @Description:新增
     */
    public void add(){
        setAttr("permissionID", -1);

        render("/admin/permission_input.tpl");
    }

    /**
     * @Title: save
     * @Description: 新增/编辑时的保存 (id为-1时为新增)
     */
    public void save(){
        int id = getParaToInt("permissionID");

        if(-1 == id){
            addPermission();
        } else{
            editPermission();
        }

        redirect("/permission/list");
    }

    /**
     * @Title: edit
     * @Description: 编辑
     */
    public void edit(){
        String id = getPara("id");

        Permission permission = Permission.dao.findById(id);

        setAttr("permissionID", permission.getInt("id"));
        setAttr("pmsName", permission.getStr("name"));
        setAttr("pmsIcon", permission.getStr("icon"));
        setAttr("pmsUrl", permission.getStr("url"));
        setAttr("pmsCode", permission.getStr("permission"));
        setAttr("pmsParentID", permission.getInt("parent_id"));
        setAttr("pmsLevel", permission.getInt("level"));
        setAttr("pmsType", permission.getInt("type"));
        setAttr("pmsSort", permission.getInt("sort"));
        setAttr("pmsRemark", permission.getStr("remark"));

        render("/admin/permission_input.tpl");
    }

    /**
     * @Title: addPermission
     * @Description:新增资源
     */
    @Before(Tx.class)
    public void addPermission(){
        Permission permission = new Permission();

        permission.set("name", getPara("pmsName"));
        permission.set("icon", getPara("pmsIcon"));
        permission.set("url", getPara("pmsUrl"));
        permission.set("permission", getPara("pmsCode"));
        permission.set("parent_id", getPara("pmsParentID"));
        permission.set("level", getPara("pmsLevel"));
        permission.set("type", getPara("pmsType"));
        permission.set("sort", getPara("pmsSort"));
        permission.set("remark", getPara("pmsRemark"));
        permission.set("created_by", InterfaceUtil.getAdminId());
        permission.set("created_time", new Date());

        permission.save();

        int permissionID = permission.getInt("id");

        // 新增权限时，默认在角色-权限表中新增一组关系。注意：这里角色固定为1，即最高权限-系统管理员角色。即使用其它角色新增一个资源时，也是默认赋给系统管理员角色。
        SysRolePermission rolePermission = new SysRolePermission();
        rolePermission.set("role_id", 1); // 默认为1，即最高权限-系统管理员角色。
        rolePermission.set("permission_id", permissionID);
        rolePermission.set("created_by", InterfaceUtil.getAdminId());
        rolePermission.set("created_time", new Date());

        rolePermission.save();
    }

    public void editPermission(){
        Permission permission = new Permission();

        permission.set("id", getPara("permissionID"));
        permission.set("name", getPara("pmsName"));
        permission.set("icon", getPara("pmsIcon"));
        permission.set("url", getPara("pmsUrl"));
        permission.set("permission", getPara("pmsCode"));
        permission.set("parent_id", getPara("pmsParentID"));
        permission.set("level", getPara("pmsLevel"));
        permission.set("type", getPara("pmsType"));
        permission.set("sort", getPara("pmsSort"));
        permission.set("remark", getPara("pmsRemark"));
        permission.set("last_updated_by", InterfaceUtil.getAdminId());
        permission.set("last_updated_time", new Date());

        permission.update();
    }

    /**
     * @Title: delete
     * @Description: 删除
     */
    @Before(Tx.class)
    public void delete() throws SQLException{
        String[] ids = getParaValues("ids");
        if(ids == null || ids.length <= 0){
            ajaxJsonErrorMessage("删除失败，无选中项");
        }

        boolean deleted = deletePermissionByIDs(ids);
        boolean bDel = deleteSysRolePermissionByIDs(ids);

        if(deleted && bDel){
            ajaxJsonSuccessMessage("删除成功！");
        } else{
            ajaxJsonErrorMessage("删除失败！");
            throw new SQLException("权限资源删除失败");
        }
    }

    private boolean deletePermissionByIDs(String[] ids){
        boolean deleted = true;
        for(String id : ids){
            Permission permission = new Permission();
            permission.set("id", id);
            permission.set("is_deleted", 1);
            permission.set("last_updated_by", InterfaceUtil.getAdminId());
            permission.set("last_updated_time", new Date());
            if(!permission.update()){
                deleted = false;
                break;
            }
        }

        return deleted;
    }

    /**
     * @Title: deleteSysRolePermissionByIDs
     * @Description:删除 角色-权限
     * @param ids TODO
     * @return boolean
     */
    private boolean deleteSysRolePermissionByIDs(String[] ids){
        boolean deleted = true;
        for(String id : ids){
            SysRolePermission rolePermission = new SysRolePermission();
            if(!rolePermission.deleteByRoleIdAndPermissionId("1", id)){
                deleted = false;
                break;
            }
        }

        return deleted;
    }
}
